package com.lengxf.i18n.controller;

import com.alibaba.excel.EasyExcel;
import com.lengxf.i18n.bean.ExcelDTO;
import com.lengxf.i18n.config.I18nCellWriteHandler;
import com.lengxf.i18n.listener.I18nAnalysisEventListener;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RequestMapping("excel")
@RestController
public class ExcelController {

    @PostMapping("export")
    public void export(HttpServletResponse response) throws IOException {

        //设置 response 参数
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + "123" + ".xlsx");

        //需要导出的数据
        List<ExcelDTO> dataList = List.of(
                new ExcelDTO("name1", "desc1"),
                new ExcelDTO("name2", "desc2")
        );

        //导出数据
        EasyExcel.write(response.getOutputStream(), ExcelDTO.class)
                .registerWriteHandler(new I18nCellWriteHandler())
                .sheet("测试一下").doWrite(dataList);
    }

    @PostMapping("read")
    public Object read(@RequestPart("file") MultipartFile file) throws IOException {
//        List<ExcelDTO> objects = EasyExcel.read(file.getInputStream())
//                .head(ExcelDTO.class)
//                .doReadAllSync();

        I18nAnalysisEventListener<ExcelDTO> i18nAnalysisEventListener = new I18nAnalysisEventListener<>();
        EasyExcel.read(file.getInputStream(), ExcelDTO.class, i18nAnalysisEventListener)
                .sheet().doRead();
        return i18nAnalysisEventListener.getList();
    }

}
